// \u4e00-\u9fa5] 中文验证规则
import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  data: {
    point: '', // 小区名称
    building: '', // 楼栋名称
    room: '', // 房间名称
    name: '', // 业务姓名
    gender: 1, // 性别
    mobile: '', // 手机号
    idcardFrontUrl: '', // 身份证正面
    idcardBackUrl: '', // 身份证反面
  },
  rules: {
    name: [{
      required: true,
      message: '业主姓名不能为空!'
    },
    {
      pattern: /^[\u4e00-\u9fa5]{2,5}$/,
      message: '业主姓名只能为中文!'
    },
    ],
    mobile: [{
      required: true,
      message: '业主手机号不能为空!'
    },
    {
      pattern: /^1[3-8]\d{9}$/,
      message: '请填写正确的手机号!'
    },
    ],
    idcardFrontUrl: [{
      required: true,
      message: '请上传身份证国徽面!'
    }],
    idcardBackUrl: [{
      required: true,
      message: '请上传身份证照片面!'
    }],
  },
  async onSubmit() {
    const isShow = this.validate()
    // console.log(isShow)
    if (!isShow) return
    console.log(this.data);
    const {
      __webviewId__,
      status,
      ...data
    } = this.data
    await wx.http.post('/room', data)
    wx.utils.toast('操作成功')
    setTimeout(() => {
      wx.reLaunch({
        url: '/house_pkg/pages/list/index',
      })
    }, 300);

  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({
      [type]: ''
    })
  },
  onLoad({ point, building, room, id }) {
    if (id) {
      console.log(id)
      wx.setNavigationBarTitle({
        title: '修改房屋信息'
      })
      this.getHouseDetail(id)
    } else {
      this.setData({
        point,
        building,
        room
      })
    }
  },
  async getHouseDetail(id) {
    const res = await wx.http.get('/room/' + id)
    console.log(res)
    this.setData({ ...res })
  },
  async uploadPicture(event) {
    const {
      tempFiles
    } = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera']
    })
    // console.log(tempFiles)
    if (tempFiles.length === 0) return
    wx.uploadFile({
      filePath: tempFiles[0].tempFilePath,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: 'Bearer ' + getApp().token
      },
      success: (res) => {
        console.log(res)
        const {
          data,
          code,
          message
        } = JSON.parse(res.data)
        if (code !== 10000) return wx.utils.toast('上传失败')
        this.setData({
          [event.mark.type]: data.url
        })
      }

    })
  }
})